package com.base.andlangcore.mvvm

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Operation
import com.base.andlangcore.http.Request
import com.base.andlangcore.http.RequestApollo

/**
 * 基础的ViewModel
 */
open class AndLangModel(val app: Application) : AndroidViewModel(app){
    val errMsg = MutableLiveData<String>()

    fun <T> makeCall(buildRequest: Request<T>.() -> Unit) {

        val commonRequest = Request<T>().apply(buildRequest)

        commonRequest.onStart { }

        commonRequest.onError {
            errMsg.value = it
            commonRequest.originError?.invoke(it)
        }

        commonRequest.onResponse { data ->
            data?.let {
                when (data.code) {
                    200 -> {
                        commonRequest.originResponse?.invoke(data)
                        data.data.let {
                            commonRequest.success?.invoke(data.data)
                        } ?: return@let
                    }
                    403 -> {

                    }
                    else -> commonRequest.error?.invoke(data.message)
                }
            } ?: run {
                commonRequest.error?.invoke("数据异常")
            }
        }

        commonRequest.onComplete { }

        commonRequest.toRequest(viewModelScope)

    }


    fun <T : Operation.Data> makeCallApollo(buildRequest: RequestApollo<T>.() -> Unit) {

        val commonRequest = RequestApollo<T>().apply(buildRequest)

        commonRequest.onStart { }

        commonRequest.onError {
            errMsg.value = it
            commonRequest.originError?.invoke(it)
        }

        commonRequest.onResponse { data ->
            data?.let {
                commonRequest.originResponse?.invoke(data)
                data.data.let {
                    commonRequest.success?.invoke(data.data)
                } ?: return@let

            } ?: run {
                commonRequest.error?.invoke("数据异常")
            }
        }

        commonRequest.onComplete { }

        commonRequest.toRequest(viewModelScope)

    }
}